package myjava.o_byteCodeOperate;

import javassist.*;

import java.util.Arrays;

/**
 * @Auther: cty
 * @Date: 2020/4/14 11:46
 * @Description: 测试javassist的API
 * @version: 1.0
 */
public class Javassist2 {
    // 获取当前工程路径
    static String projectPath = System.getProperty("user.dir");
    // 指定文件输出路径
    static String path = projectPath+"\\DynamicCompile\\myjava.p_classLoader.mycode\\";

    /**
     * 处理类的基本用法
     * @throws Exception
     */
    public static void test01() throws Exception{
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(User.class));  // 将指定类载入处理池
        System.out.println(pool);  // out: [class path: com.cty.User.class;java.lang.Object.class;]
        CtClass cc = pool.get("com.cty.User");  // 加载现有类


        byte[] bytes = cc.toBytecode();  // 转化成字节码
        System.out.println(Arrays.toString(bytes));  // out: [-54, -2, -70, -66, 0, 0, 0, 57, 0, 38,...

        System.out.println(cc.getName()); //获取类名  out: com.cty.User
        System.out.println(cc.getSimpleName()); //获取简要类名  User
        System.out.println(cc.getSuperclass()); //获得父类  out: javassist.CtClassType@5d6f64b1[public class java.lang.Object fields= ...
        System.out.println(cc.getInterfaces()); //获得接口  out: [Ljavassist.CtClass;@5eb5c224
    }

    /**
     * 测试产生新的方法
     * @throws Exception
     */
    public static void test02() throws Exception{
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(User.class));  // 将指定类载入处理池
        System.out.println(pool);  // out: [class path: com.cty.User.class;java.lang.Object.class;]
        CtClass cc = pool.get("com.cty.User");  // 加载现有类

//		CtMethod m = CtNewMethod.make("public int add(int a,int b){return a+b;}", cc);

        CtMethod m = new CtMethod(CtClass.intType,"add", new CtClass[]{CtClass.intType,CtClass.intType},cc);
        m.setModifiers(Modifier.PUBLIC);
        m.setBody("{return $1+$2;}");

        cc.addMethod(m);

        //通过反射调用新生成的方法
//        Class clazz = cc.toClass();  // error: Caused by: java.lang.LinkageError: loader 'app' attempted duplicate class definition for com.cty.User. (com.cty.User is in unnamed module of loader 'app')
//        Object obj = clazz.newInstance();  //通过调用Emp无参构造器，创建新的Emp对象
//        Method method = clazz.getDeclaredMethod("add", int.class,int.class);
//        Object result = method.invoke(obj, 200,300);
//        System.out.println(result);
    }

    /**
     * 修改已有的方法的信息，修改方法体的内容
     * @throws Exception
     */
    public static void test03() throws Exception{
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(User.class));  // 将指定类载入处理池
        System.out.println(pool);  // out: [class path: com.cty.User.class;java.lang.Object.class;]
        CtClass cc = pool.get("com.cty.User");  // 加载现有类

        CtMethod cm = cc.getDeclaredMethod("sayHello",new CtClass[]{CtClass.intType});
        cm.insertBefore("System.out.println($1);System.out.println(\"start!!!\");");
        cm.insertAt(24, "int b=3;System.out.println(\"b=\"+b);");
        cm.insertAfter("System.out.println(\"end!!!\");");

        //通过反射调用新生成的方法
//        Class clazz = cc.toClass();
//        Object obj = clazz.newInstance();  //通过调用Emp无参构造器，创建新的Emp对象
//        Method method = clazz.getDeclaredMethod("sayHello", int.class);
//        method.invoke(obj, 300);
    }

    /**
     * 属性的操作
     * @throws Exception
     */
    public static void test04() throws Exception{
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(User.class));  // 将指定类载入处理池
        System.out.println(pool);  // out: [class path: com.cty.User.class;java.lang.Object.class;]
        CtClass cc = pool.get("com.cty.User");  // 加载现有类

//		CtField f1 = CtField.make("private int empno;", cc);
        CtField f1 = new CtField(CtClass.intType,"salary",cc);
        f1.setModifiers(Modifier.PRIVATE);
        cc.addField(f1);

//		cc.getDeclaredField("ename");   //获取指定的属性

        //增加相应的set和get方法
        cc.addMethod(CtNewMethod.getter("getSalary", f1));;
        cc.addMethod(CtNewMethod.getter("setSalary", f1));;

    }

    /**
     * 构造方法的操作
     * @throws Exception
     */
    public static void test05() throws Exception {
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(User.class));  // 将指定类载入处理池
        System.out.println(pool);  // out: [class path: com.cty.User.class;java.lang.Object.class;]
        CtClass cc = pool.get("com.cty.User");  // 加载现有类

        CtConstructor[] cs = cc.getConstructors();
        for (CtConstructor c : cs) {
            System.out.println(c.getLongName());
            // out:
            // com.cty.User(int,java.lang.String,java.lang.String)
            // com.cty.User()
        }
    }

    /**
     * 注解的操作
     * @throws Exception
     */
    public static void test06() throws Exception{
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(User.class));  // 将指定类载入处理池
        System.out.println(pool);  // out: [class path: com.cty.User.class;java.lang.Object.class;]
        CtClass cc = pool.get("com.cty.User");  // 加载现有类

        Object[] all = cc.getAnnotations();
        Author a = (Author)all[0];
        String name = a.name();
        int year = a.year();
        System.out.println("name: " + name + ", year: " + year);  // out: name: cty, year: 2020

    }

    public static void main(String[] args) throws Exception {
        test02();
    }
}
